const cors = require("@koa/cors");

const tokenHeader = require("../config/tokenHeader-constants");

// 创建通用CORS中间件·
function createCorsMiddleware(options = {}) {
  const {
    // allowOrigins = "http://localhost:5173", // 允许的来源
    allowOrigins = "*", // 允许的来源
    allowMethods = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], // 允许的HTTP方法
    // allowHeaders = ["Content-Type", "Authorization"], // 允许的请求头
    allowHeaders = "*",
    exposeHeaders = [
      "Content-Type",
      "Authorization",
      "Token",
      tokenHeader.AccessToken,
      tokenHeader.AccessTokenInvalid,
      tokenHeader.RefreshToken,
      tokenHeader.RefreshTokenInvalid,
    ], // 设置允许暴露的头
    credentials = true, // 允许设置资格证明如果为true，allowedOrigins("*")方法不能再设置为通配符
    maxAge = 3600,
  } = options;

  return cors({
    origin: allowOrigins,
    allowMethods: allowMethods,
    allowedHeaders: allowHeaders,
    exposeHeaders: exposeHeaders,
    credentials: credentials,
    maxAge: maxAge,
  });
}

module.exports = {
  createCorsMiddleware,
};
